package com.boyi.shared;

import org.springframework.context.ApplicationContext;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

public class CM {
    private static ApplicationContext context;

    public static <T> Map<String, T> getBeanByType(Class<T> type) {
        return context.getBeansOfType(type);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBeanByType(Class clazz, Type type) {
        String[] beanNamesForType = context.getBeanNamesForType(clazz);
        for (String s : beanNamesForType) {
            // 根据名字获取bean
            Object bean = context.getBean(s);
            // 取得该bean 的泛型类型
            Type type1 = bean.getClass().getGenericSuperclass();
            Class c = (Class) type1;
            Type superClass = c.getGenericSuperclass();
            //得到当前类上所有的泛型类型Class
            Type[] types = ((ParameterizedType) superClass).getActualTypeArguments();
            //得到具体传入的泛型类Class对象
            if (clazz.isAssignableFrom(bean.getClass()) && type.equals(types[0])) {
                return (T) bean;
            }
        }
        return null;
    }

    public static <T> T getBean(Class<T> type) {
        return context.getBean(type);
    }

    public static void setContext(ApplicationContext context) {
        CM.context = context;
    }

}
